package scatter.interview.rest.interview.i1_queue;

/**
 * 顺序队列
 * Created by yangwei
 * Created at 2020/12/2 15:53
 */
public class SeqQueue<T> extends AbstractQuene<Integer,Integer,T>{

    private Object[] data;


    /**
     * 构造
     */
    public SeqQueue(Integer size) {
        this.rear = 0;//队尾为0
        this.front = 0;//队首为0
        data = new Object[size];
    }

    /**
     * 入队
     *
     * @return boolean
     */
    @Override
    public boolean push(T t) {
        if (this.rear >= this.data.length) {
            return false;
        } else {
            data[rear++] = t;
            return true;
        }
    }

    /**
     * 出队
     *
     * @return t 队首元素
     */
    @Override
    public T pop() {
        if (this.front.equals( this.rear)) {
            return null;
        } else {

            T t = (T) data[front];
            data[front] = null;
            front++;
            if (this.front.equals( this.rear)) {
                front = 0;
                rear = 0;
            }
            return t;
        }
    }

    public static void main(String[] args) {
        SeqQueue<String> sQueue = new SeqQueue<>(10);
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        sQueue.push("1");
        sQueue.push("2");
        sQueue.push("3");
        sQueue.push("4");
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
        System.out.println(sQueue.pop());
    }
}
